<!DOCTYPE html>
<html lang="en">
  <head>
    <meta charset="UTF-8" />
    <meta name="viewport" content="width=device-width, initial-scale=1.0" />
    <title>Document</title>
    <style>
      .message {
        display: none;
      }
      .error ~ .message {
        display: inline;
      }
      .success {
        border: 2px solid greenyellow;
        outline: none;
      }
    </style>
  </head>
  <body>
    <h1>表单验证</h1>

    <form name="form">
      <p>
        用户 <input type="text" name="username" />
        <span class="message">用户2-18位</span>
      </p>
      <p>
        邮箱 <input type="text" name="email" />
        <span class="message">邮箱格式错误</span>
      </p>
      <p>
        <button type="button" name="submitBtn">提交</button>
      </p>
    </form>

    <script>
      const form = document.form;

      // rule参数类型：正则表达式，回调函数
      function valid(el, rule) {
        const r = rule.test(el.value);
        if (r) {
          el.classList.add("success");
          el.classList.remove("error");
        } else {
          el.classList.add("error");
          el.classList.remove("success");
        }
        return r;
      }

      form.submitBtn.onclick = function () {
        valid(form.username, /^[a-z]{2,18}$/);

        const regEmail = /^\w+@\w+\.\w+$/;
        if (regEmail.test(form.email.value)) {
          form.email.classList.add("success");
          form.email.classList.remove("error");
        } else {
          form.email.classList.add("error");
          form.email.classList.remove("success");
          return;
        }

        console.log("success成功");
      };
    </script>
  </body>
</html>
